<template>
    <div class="login-box">
        <div class="form-box">
            <div class="logo-box">
                <img class="logo" src="@/assets/header/logo.svg">
            </div>

            <div>
                <el-input v-model="form.username" placeholder="用户名"></el-input>

            </div>
            <div>
                <el-input type="password" v-model="form.password" placeholder="密码"></el-input>

            </div>

            <div class="bottom-box">
                <el-link type="danger" @click="router.push({name: 'register'})">还没有账号？去注册</el-link>
            </div>

            <div class="button-box">
                <el-button type="primary" style="width:80%;" @click="loginHandler">登录</el-button>
            </div>

        </div>
    </div>
</template>

<script setup>
import { onMounted, reactive } from 'vue';
import router from '@/router';
import {login} from '@/api/user-service/user'
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/stores/user'

onMounted(() => {
    let isLogin = store.isLogin

    if(isLogin){
        console.log("is login", isLogin)
        router.push('/')
    }
})

const form = reactive({
    username: '',
    password: '',
})

const store = useUserStore()

function loginHandler(){
    let username = form.username
    let password = form.password
    
    let params = {
        username,
        password
    }

    login(params)
    .then(res => {
        if(res.code == 200){
            ElMessage.success(res.msg)

            let token = res.data.token
            let avatar = res.data.avatar
            let username = res.data.username

            let user = {
                avatar,
                username
            }
            console.log(store.getAvatar)

            store.setUser(user)
            console.log(store.getAvatar)
            
            sessionStorage.setItem('token', token)

            sessionStorage.setItem('avatar', avatar)
            sessionStorage.setItem('username', username)
        }

        else ElMessage.error(res.msg)
    })
}
</script>

<style scoped>
    .login-box{
        height: 100%;

        display:flex;
        
        justify-content: center;
        align-items: center;

        background: linear-gradient(118deg, #1a2037, #2b2020, #000000);
        border-radius: 8px;
    }

    .form-box{
        width:30%;
        height: 100%;

        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }

    .form-box .logo-box{
        text-align: center;
    }

    .form-box > div{
        margin-bottom: 15px;;
        width:100%;
    }

    .form-box .button-box{
        text-align: center;
    }

    .form-box .bottom-box{
        text-align: right;
    }
</style>